import uvicorn
from fastapi import FastAPI, APIRouter
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
import secrets
import time

# 导入路由模块
from login_and_register.login import appLogin
from login_and_register.register import appRegister
from EnvironmentData_update import appEnvironmentUpdate
from user_getdata.getdata import appGetData
# ================= 应用初始化 =================
app = FastAPI(
    title="植物管家 API",
    description="智能植物养护系统后端接口",
    version="1.0.0",
    docs_url="/docs",  # 启用 Swagger 文档
    redoc_url="/redoc"  # 启用 ReDoc 文档
)

print(" 植物管家 API 服务初始化中...")

# ================= 中间件配置 =================
# CORS 中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境建议指定具体域名
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)
print(" CORS 中间件已配置")

# Session 中间件配置
app.add_middleware(
    SessionMiddleware,
    secret_key="mogutunhucunzhangiscool",  # 生产环境请修改为随机密钥
    session_cookie="plant_session",
    max_age=3600  # 1小时过期
)
print("Session 中间件已配置")

# ================= 路由注册 =================
# 包含路由
app.include_router(appLogin, prefix="/api", tags=["用户认证"])
app.include_router(appRegister, prefix="/api", tags=["用户认证"])
app.include_router(appEnvironmentUpdate, prefix="/api", tags=["环境数据"])
app.include_router(appGetData,prefix='/api',tags=["用户信息获取"])
print("所有路由已注册")


# ================= 全局路由 =================
@app.get("/")
async def root():
    """
     根路径 - API 服务状态检查
    """
    return {
        "message": "植物管家 API 服务运行正常",
        "status": "running",
        "version": "1.0.0",
        "timestamp": time.time(),
        "docs": "/docs",
        "health": "/health"
    }


@app.get("/health")
async def health_check():
    """
     健康检查端点
    """
    return {
        "status": "healthy",
        "service": "植物管家 API",
        "timestamp": time.time(),
        "uptime": "运行中"
    }


@app.get("/status")
async def get_status():
    """
     获取系统状态模拟数据
    """
    return {
        "soil_moisture": 45,
        "temperature": 25,
        "status": "happy",
        "air_humidity": 60,
        "light_intensity": 800,
        "timestamp": time.time(),
        "message": "植物生长状态良好"
    }


@app.get("/api/info")
async def api_info():
    """
     API 接口信息
    """
    return {
        "api_name": "植物管家 API",
        "version": "1.0.0",
        "description": "智能植物养护系统后端接口",
        "endpoints": {
            "auth": {
                "login": "POST /api/login",
                "register": "POST /api/register"
            },
            "environment": {
                "update": "POST /api/environment",
                "current": "GET /api/environment/current"
            },
            "system": {
                "health": "GET /health",
                "status": "GET /status",
                "info": "GET /api/info"
            }
        }
    }


# ================= 启动应用 =================
if __name__ == "__main__":
    print("=" * 50)
    print(" 植物管家 API 服务启动完成!")
    print(" API 文档: http://localhost:8000/docs")
    print(" 健康检查: http://localhost:8000/health")
    print(" 首页: http://localhost:8000/")
    print("=" * 50)

    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        reload=True,  # 开发环境启用热重载
        log_level="info"
    )